import { useState, useEffect, useCallback, useMemo } from "react"
import RoleSearch from "./role/index"
import dayjs from "dayjs"
import { Card, Upload, Button, message, Table, Popconfirm, Pagination, Tag, Space } from "antd"
import { useNavigate } from "react-router-dom"
import { PlusOutlined, UploadOutlined, DownloadOutlined } from "@ant-design/icons"
import { getClass, getType, getDropt, delClass } from "@/api/index"
import { exportFile } from "@/api/index"
const Application = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const useStatus = JSON.parse(localStorage.getItem("role"))[0].status
  let search = JSON.parse(sessionStorage.getItem("search")) || {}
  const columns = [
    {
      width: 150,
      title: "创建时间",
      dataIndex: "create_time",
      render: (text) => (text ? dayjs(text).format("YYYY-MM-DD HH:mm:ss") : ""),
      fixed: "left"
    },
    {
      width: 100,
      title: "教室名称",
      dataIndex: "class_name"
    },
    {
      title: "所属院校",
      dataIndex: "apply_department",
      render: (text) => (text ? text.deparment_name : "")
    },
    {
      title: "可用状态",
      dataIndex: "current_state",
      render: (text) =>
        text === 0 ? <Tag color="#87d068">可用</Tag> : <Tag color="rgb(56, 117, 246)">使用中</Tag>
    },
    {
      title: "使用类型",
      dataIndex: "availabel_types",
      render: (text) => (text && text ? text.type_name : false)
    },
    {
      width: 150,
      fixed: "right",
      title: "更新时间",
      dataIndex: "update_time",
      render: (text) => (text ? dayjs(text).format("YYYY-MM-DD HH:mm:ss") : "")
    },
    {
      fixed: "right",
      title: "操作",
      width: 150,
      render: (text, record) => {
        return (
          <Space size={"small"}>
            <a
              disabled={useStatus === 1}
              onClick={() => {
                navigate("/admin/classroom/updateClass/?id=" + record._id)
              }}
            >
              修改
            </a>
            <a
              onClick={() => {
                navigate("/admin/classroom/details/?id=" + record._id)
              }}
            >
              {" "}
              查看
            </a>
            <Popconfirm
              description="是否删除?"
              onConfirm={() => delConfirm(record._id)}
              onCancel={() => false}
              okText="是"
              cancelText="否"
            >
              <a disabled={useStatus === 1}>删除</a>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  const applyType = [
    {
      label: "可使用",
      value: 0
    },
    {
      label: "使用中",
      value: 1
    }
  ]
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(6)
  const [total, setTotal] = useState(0)
  const [list, setList] = useState([])
  const [useType, setType] = useState([])
  const [dropt, setDropt] = useState([])
  useEffect(() => {
    setLoading(true)
    let timer = setTimeout(() => {
      setLoading(false)
    }, 2000)
    getDeparmentList()
    getTypes()
    return () => clearTimeout(timer)
  }, [])
  useEffect(() => {
    getList()
  }, [page])
  const getList = async (value) => {
    const data =
      value === undefined
        ? await getClass({ page, limit: pageSize })
        : await getClass({ page, limit: pageSize, ...value })
    setList(data.data)
    setPage(data.page)
    setPageSize(data.limit)
    setTotal(data.total)
  }
  const getDeparmentList = async () => {
    const { data } = await getType()
    setDropt(data)
  }
  const getTypes = async () => {
    const { data } = await getDropt()
    setType(data)
  }
  // 使用useCallback函数，当onFinish函数发生变化时，执行onFinish函数
  const onFinish = useCallback(
    (value) => {
      // 从value中过滤出key和value不为undefined的项
      let obj = Object.fromEntries(Object.entries(value).filter((item) => item[1] !== undefined))
      if (areObjectsEqual(obj, search)) {
        return false
      } else {
        getList({ ...obj })
        sessionStorage.setItem("search", JSON.stringify(obj))
      }
    },
    [getList]
  )
  // 使用useMemo函数，当onFinish函数发生变化时，执行onFinish函数
  const onFinishFailed = useMemo(() => onFinish, [onFinish])
  function areObjectsEqual(obj1, obj2) {
    // 检查属性数量是否相等
    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)
    if (keys1.length !== keys2.length) {
      return false
    }
    // 检查每个属性的值是否相等
    for (let key of keys1) {
      if (obj1[key] !== obj2[key]) {
        return false
      }
    }
    // 所有属性都相等
    return true
  }
  const delConfirm = async (id) => {
    setLoading(true)
    await delClass({ _id: id }).then(() => {
      setLoading(false)
    })
    getList()
  }
  const onChange = (pageNumber) => {
    setPage(pageNumber)
  }
  const classSearchColums = [
    {
      label: "教室名称",
      name: "class_name",
      type: "input",
      placeholder: "请输入教室名称"
    },
    {
      label: "教室类型",
      name: "apply_department",
      type: "select",
      options: useType,
      placeholder: "请选择所属院校",
      fieldNames: {
        label: "deparment_name",
        value: "_id"
      }
    },
    {
      label: "可用状态",
      name: "current_state",
      type: "select",
      options: applyType,
      placeholder: "请选择可用状态"
    },
    {
      label: "使用类型",
      name: "availabel_types",
      type: "select",
      options: dropt,
      placeholder: "请选择使用类型",
      fieldNames: {
        label: "type_name",
        value: "_id"
      }
    }
  ]
  const props = {
    name: "file",
    action: "http://localhost:3666/classroom/importExcel",
    headers: {
      authorization: "authorization-text"
    },
    onChange(info) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === "done") {
        message.success(`${info.file.name} 文件上传成功`)
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 文件上传失败`)
      }
    }
  }
  const fileDownload = async () => {
    await exportFile()
  }
  return (
    <div style={{ paddingBottom: 56, height: "100%" }}>
      <div className="role-list-title">
        <h3>教室模块</h3>
      </div>
      <div>
        <RoleSearch columns={classSearchColums} onSearch={onFinishFailed} page={page} />
      </div>
      <Card style={{ width: "100%", border: "none" }}>
        <Button
          disabled={useStatus === 1}
          icon={<PlusOutlined />}
          type="primary"
          onClick={() => {
            navigate("/admin/classroom/addClass")
          }}
        >
          教室申请
        </Button>
        <div style={{ display: "inline-block", float: "right" }}>
          <Button onClick={() => fileDownload()}>
            <DownloadOutlined />
            文件下载
          </Button>
          <Upload {...props}>
            <Button icon={<UploadOutlined />} style={{ marginLeft: 12 }}>
              文件上传
            </Button>
          </Upload>
        </div>
      </Card>
      <Table
        columns={columns}
        dataSource={list}
        rowKey="_id"
        pagination={false}
        loading={loading}
        scroll={{
          x: 1200,
          y: 335
        }}
      />
      <Pagination
        showQuickJumper
        current={page}
        total={total}
        pageSize={pageSize}
        pageSizeOptions={["2", "5", "10", "20"]}
        onChange={onChange}
        style={{
          marginTop: 24,
          float: "right"
        }}
        showTotal={(total) => `共 ${total} 条数据`}
      />
    </div>
  )
}

export default Application
